// const API_URL = 'http://192.168.1.67:8080/hxq/'      // 测试
const API_URL = 'https://boss.haoxuequ.net/hxq/' // 正式
//GET请求
function GET(url, params, message, config) {
  return request(url, params, message, config, 'GET')
}
//POST请求
function POST(url, params, message, config) {
  return request(url, params, message, config)
}

function request(url, params = {}, message = '', config = {}, method = 'POST') {
  if (message) {
    wx.showToast({
      icon: 'loading',
      duration: 100000,
      title: message,
      mask: true
    })
  }
  return new Promise((ok, fail) => {
    let sessionId = wx.getStorageSync('sessionId')
    let user = wx.getStorageSync('user')
    let header = {
      'Content-Type': 'application/x-www-form-urlencoded'
    }

    if (sessionId) {
      header['Cookie'] = `SESSION=${sessionId}`
    }

    if (user) {
      params = Object.assign(
        {
          studentId: user.id,
          student_id: user.id,
          userId: user.id,
          userType: user.roleId,
          user_type: user.roleId,
          schoolId: user.schoolId,
          school_id: user.schoolId,
          classId: user.classId,
          class_id: user.classId
        },
        params
      )
    }

    wx.request(
      Object.assign({
        url: API_URL + url,
        data: params,
        header: header,
        method: method,
        success(res) {
          if (res.data.code === 200) {
            ok(res.data.data)
          } else if (res.data.code === 402) {
            wx.showModal({
              title: '用户已过期，请重新登录！',
              showCancel: false,
              icon: 'none',
              success: () => {
                wx.reLaunch({
                  url: '/pages/login/login'
                })
              }
            })
          } else {
            fail(res)
          }
        },
        fail(err) {
          fail(err)
        },
        complete() {
          // 接口调用完成后
          if (message) {
            wx.hideToast()
          }
        }
      })
    )
  })
}

module.exports = {
  get: GET,
  post: POST
}
